<style lang="less">
	@import "../../variables.less";
	@import "../../resource/common.less";

	@currentWidth: 550px;
</style>
<template>
	<div class="AddRequest">
		<div class="mainContent">
			<div class="head">添加维修单</div>
			<Form :label-width="120" :modal="info" label-position="right">
				<FormItem label="选择位置">
					<Cascader :data="floorTree" @on-change="focusToRoom" clearable placeholder="报修房间"
						v-model="info.space" />
				</FormItem>
				<FormItem label="选择设备">
					<Cascader :data="deviceTree" :load-data="loadDevice" clearable placeholder="报修设备"
						v-model='info.device' />
				</FormItem>
				<FormItem label="截止日期">
					<DatePicker :options="option" v-model="info.deadline" />
				</FormItem>
				<FormItem label="优先级">
					<Select v-model="info.priority">
						<Option :value="0">特急</Option>
						<Option :value="1">紧急</Option>
						<Option :value="2">普通</Option>
					</Select>
				</FormItem>
				<FormItem label="问题描述">
					<AutoComplete :data="resolve" :transfer=false @on-search="searchDescribe" v-model="info.describe" />
				</FormItem>
				<FormItem label="上传文件">
					<Upload :max-size=10240 :on-exceeded-size="handleExceeded" :on-preview='previewFile'
						action="/file/upload/" multiple ref="upload" with-credentials>
						<Button ghost>上传</Button>
					</Upload>
				</FormItem>
				<FormItem label="">
					<div style="text-align: right">
						<Button :loading="loading" @click="submit" ghost>创建</Button>
						<Button :loading="loading" @click="$router.go(-1)" ghost style="margin-left: 6px">返回</Button>
					</div>
				</FormItem>
			</Form>
		</div>
		<Modal title="预览图片" v-model="visible">
			<img :src="imageUrl" alt="" width="350">
		</Modal>
	</div>
</template>
<script lang="ts">
	import { Component, Vue } from "vue-property-decorator";
	import request from "../../request";
	import moment from "moment";
	import qs from "qs";
	import {
		AutoComplete,
		Button,
		Cascader,
		DatePicker,
		Form,
		FormItem,
		Modal,
		Option,
		Select,
		Upload
	} from "view-design";
	import { Route } from "vue-router";

	interface Tree {
		label:string,
		value:number,
		type:"system" | "category" | "device",
		loading?:boolean,
		children?:Tree[]
	}

	interface resolve {
		what:string,
		how:string,
		why:string
	}

	@Component({
		components: {
			Form,
			FormItem,
			Select,
			Option,
			DatePicker,
			AutoComplete,
			Upload,
			Button,
			Cascader,
			Modal
		}
	})
	export default class AddRequest extends Vue {
		floorTree:Tree[] = [];
		deviceTree:Tree[] = [];
		resolve:string[] = [];
		info = {
			space: [],
			device: [],
			deadline: new Date(Date.now() + 7 * 24 * 3600 * 1000),
			priority: 2,
			describe: "",
			fileList: []
		};
		loading:boolean = false;
		imageUrl:string = "";
		visible:boolean = false;
		readonly option = {
			disabledDate (date:Date):boolean {
				return date && date.valueOf() < Date.now();
			}
		};
		private resolveSource:resolve[] = [];
		private readonly listener = this.$store.subscribe(mutation => {
			if (mutation.type === "findRoom" && mutation.payload.path) {
				this.info.space = mutation.payload.path;
			}
		});

		loadDevice (item:Tree, callback:Function) {
			item.loading = true;
			let url:string;
			let params;
			if (item.type === "system") {
				url = "/device/devicecategory/";
				params = {
					DeviceType__mepsystemtype: item.value,
					DeviceType__Device__room__floor: this.$store.state.floorValue,
					DeviceType__Device__room: this.info.space[ 2 ]
				};
			} else {
				url = "/device/device2/";
				params = {
					devicetype__device_category: item.value,
					room: this.info.space[ 2 ],
					room__floor: this.$store.state.floorValue
				};
			}
			request({
				url,
				params
			}).then(({ data }) => {
				if (url === "/device/devicecategory/") {
					item.children = data.map((t:any):Tree => ({
						label: t.name,
						value: t.id,
						loading: false,
						type: "category",
						children: []
					}));
				} else {
					item.children = data.results.map((t:any):Tree => ({
						label: t.device_category_name + t.code,
						value: t.id,
						type: "device"
					}));
				}
				item.loading = false;
				callback();
			});
		}

		getCurrentDeviceTree () {
			request({
				url: "/device/mepsystemtype/",
				params: {
					DeviceType__Device__room: this.info.space[ 2 ]
				}
			}).then(({ data }) => {
				this.deviceTree = data.map((t:any) => ({
					label: t.name,
					value: t.id,
					type: "system",
					loading: false,
					children: []
				}));
			});
		}

		searchDescribe (text:string) {
			if (text === "") {
				this.resolve = [];
			} else {
				let regexp:RegExp = new RegExp(text);
				let set:Set<string> = new Set();
				this.resolveSource.forEach(t => {
					if (regexp.test(t.what)) {
						set.add(t.what);
					}
				});
				if (set.size === 0) {
					set.add("没有相关建议");
				}
				this.resolve = Array.from(set);
			}
		}

		focusToRoom (value:number[]) {
			if (value && value.length === 3) {
				request(`/space/room/${ value[ 2 ] }/`).then(({ data }) => {
					this.$store.commit("findRoom", { id: data.room_guid, floor: value[ 1 ] });
				});
			}
			this.getCurrentDeviceTree();
		}

		previewFile (file:any) {
			let url = file.response.data.fileurl;
			if (!file.response.data.image) {
				window.open(url);
			} else {
				this.imageUrl = url;
				this.visible = true;
			}
		}

		handleExceeded () {
			this.$Notice.error({ desc: "文件大小超出限制" });
		}

		submit () {
			this.loading = true;
			const tempData = this.info;
			const data = {
				opt: "create",
				describe: tempData.describe,
				mepsystem: tempData.device[ 1 ],
				priority: tempData.priority,
				docids: (this.$refs.upload as any).fileList.map((t:any) => t.response.data.docId),
				device: tempData.device[ 2 ],
				space: tempData.space,
				deadline: tempData.deadline ? moment(tempData.deadline).format("YYYY-MM-DD") : null
			};
			request({
				url: "/repair/eventopt/",
				method: "post",
				transformRequest: [ function (data) {
					return qs.stringify(data, { arrayFormat: "brackets" });
				} ],
				data
			}).then(() => {
				this.$router.go(-1);
			});
		}

		mounted () {
			request("/prj/facilityfloorrooms/").then(({ data }) => {
				this.floorTree = [ data.data[ 0 ] ];
			});
			request("/repair/rest/requirement/").then(({ data }) => {
				this.resolveSource = data;
			});
			this.getCurrentDeviceTree();
		}

		beforeRouteLeave (to:Route, from:Route, next:Function) {
			this.listener();
			next();
		}
	}
</script>
